package DataStructure.LinkedLearning.SingleLinkedList.TheMiddleEle;

import DataStructure.LinkedLearning.SingleLinkedList.JudgeTheRing.Node;

/**
 *  学习 用快慢指针找出单链表的中间元素
 */
public class Demo {
    public static void main(String[] args) {
        Node node7 = new Node(7, null);
        Node node6 = new Node(6, node7);
        Node node5 = new Node(5, node6);
        Node node4 = new Node(4, node5);
        Node node3 = new Node(3, node4);
        Node node2 = new Node(2, node3);
        Node node1 = new Node(1, node2);

        // 使用快慢指针
        System.out.println(middleEle(node1));

    }

    public static Node middleEle(Node head) {
        // 设置快慢指针
        Node fast = head;
        Node slow = head;
        // 两个判断条件不能省略
        while(fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 因为快指针移动是慢指针的两倍
        // 所以当快指针移动到末尾时，慢指针就在单链表的中间位置
        return slow;
    }
}
